package com.villaday.idf.fragment;


import android.app.Activity;
import android.content.Intent;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.activity.BackHandlerHelper;
import com.villaday.idf.activity.FragmentBackHandler;
import com.villaday.idf.activity.HouseDetailsActivityFor3;
import com.villaday.idf.activity.WineShopDetailsActivity;
import com.villaday.idf.adapter.FavoriteListFindAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseFragment;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.DividerItemDecoration.RVItemDecoration;
import com.villaday.idf.custom.pop.SharePop;
import com.villaday.idf.model.Member_favor_listEntity;
import com.villaday.idf.model3.AllPostersEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ShareUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.Unbinder;
import byc.imagewatcher.ImageWatcher;
import io.reactivex.functions.Consumer;
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;

import static android.app.Activity.RESULT_OK;

/**
 * 房源
 */
public class FangYuanFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OkHttpUtil.OnDataListener, OnAdapterCallbackListener, AbsRecyclerViewAdapter.OnItemClickListener, View.OnClickListener , FragmentBackHandler {

    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    Unbinder unbinder;

    private ImageWatcher vImageWatcher;
    private AllPostersEntity.BodyBean allPostersEntity;
    private LoadingDialog loadingDialog;
    private Gson gson = new GsonBuilder().create();

    private int pageNo = 1;
    private int nextIndex = 1;
    private int pageSize = 3;
    private int currentPosition = -1;
    List<Member_favor_listEntity.BodyEntity.ListEntity> data = new ArrayList();
    private FavoriteListFindAdapter favoriteListFindAdapter;
    private StatusLayoutManager statusLayoutManager;

    public FangYuanFragment() {
        // Required empty public constructor
    }

    public static FangYuanFragment instance() {
        FangYuanFragment fangYuanFragment = new FangYuanFragment();
        return fangYuanFragment;
    }


    @Override
    protected int getViewResId() {
        return R.layout.fragment_fang_yuan;
    }

    @Override
    protected void init(View v) {
        initSharePop();
        statusLayoutManager = setupDefaultStatusLayoutManager(srl, new OnStatusChildClickListener() {
            @Override
            public void onEmptyChildClick(View view) {

            }

            @Override
            public void onErrorChildClick(View view) {
                loadData();
            }

            @Override
            public void onCustomerChildClick(View view) {

            }
        });
        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getActivity().getFragmentManager(), "loading");
        srl.setOnRefreshListener(this);

        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        favoriteListFindAdapter = new FavoriteListFindAdapter(getContext(), this, this);
        rv.setAdapter(favoriteListFindAdapter);

        rv.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(getContext(), 1), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(getContext(), 1)));
        favoriteListFindAdapter.setOnItemClickListener(this);
       /* View inflate = View.inflate(getContext(), R.layout.recycle_head, null);
        homeListSaleAdapter.addHeaderView(inflate);*/
        favoriteListFindAdapter.setEmptyView(R.layout.empty_tips);
        favoriteListFindAdapter.setEmptyTips(R.id.tv_emptyTips, "没有更多了");
        favoriteListFindAdapter.setEmptyView2(R.layout.empty_order_tips, true, R.id.tv_perchase);
        favoriteListFindAdapter.setEmptyTips(R.id.tv_emptyTips, "您还没有心仪的房源");
        favoriteListFindAdapter.setEmptyTips(R.id.tv_perchase, "去找房源吧");
        favoriteListFindAdapter.setOnBtnListener(new AbsRecyclerViewAdapter.OnBtnListener() {
            @Override
            public void function() {
                getActivity().setResult(RESULT_OK);
                getActivity().onBackPressed();
            }
        });
    }

    @Override
    protected void loadData() {
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", pageSize + "");
        OkHttpUtil.getJSON(getContext(), Constant.URL.member_favor_list, map, this);
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        nextIndex = 1;
        getData();
    }

    //rv item 点击事件
    @Override
    public void onItemClick(View v, int position) {
        currentPosition = position;
        if (data.get(currentPosition).getModelType()==7){
            Intent intent = new Intent(getContext(), WineShopDetailsActivity.class);

            intent.putExtra("hotelId", data.get(currentPosition).getId());
            intent.putExtra("brokerAge", data.get(currentPosition).getBrokerAgeAmountValue());

            startActivity(intent);
        }else {
            Intent intent = new Intent(getContext(), HouseDetailsActivityFor3.class);
            intent.putExtra("type", 0);
            intent.putExtra("houseId", data.get(position).getHouse().getId());
            intent.putExtra("presellProduct", data.get(position).getModelType() == 52);

            intent.putExtra("brokerAge", data.get(position).getBrokerAge());
            intent.putExtra("persellId", data.get(position).getId());
            startActivityForResult(intent, 123);
        }


    }
    private void initSharePop() {
        mRxManager.on("sharepopEntity", new Consumer<AllPostersEntity.BodyBean>() {

            @Override
            public void accept(AllPostersEntity.BodyBean bodyBean) throws Exception {

                allPostersEntity = bodyBean;
            }
        });
        mRxManager.on("sharepop", new Consumer<ImageWatcher>() {
            @Override
            public void accept(ImageWatcher imageWatcher) throws Exception {
                vImageWatcher = imageWatcher;
                vImageWatcher.setImageWatcherOndismiss(new ImageWatcher.ImageWatcherDiss() {
                    @Override
                    public void onImageWatcherDiss() {
                        if (allPostersEntity!=null){
                            SharePop sharePop = new SharePop(FangYuanFragment.this,getActivity(), getActivity(), allPostersEntity);
                            sharePop.showPopupWindow();
                        }
                    }
                });
            }
        });
    }
    @Override
    public boolean onBackPressed() {
        if (vImageWatcher == null) {
            return false;
        } else {
            // 当确认没有子Fragmnt时可以直接return false
            if (!vImageWatcher.handleBackPressed()) {
                return BackHandlerHelper.handleBackPress(this);
            } else {
                return !BackHandlerHelper.handleBackPress(this);
            }
        }
    }
    @Override//rv 里面控件  喜欢和分享
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_tuiguang: {
                currentPosition = (int) v.getTag();

                ////2 小区，3 房源 ，7 酒店，52 特卖(预售)
                ShareUtils.getData(FangYuanFragment.this, (AppCompatActivity) getActivity(), data.get((Integer) v.getTag()).getModelType()+"", data.get((Integer) v.getTag()).getId());


               /* if (data.get(currentPosition).getModelType()==7){

                    Intent intent = new Intent(getContext(), WineShopDetailsActivity.class);
                    intent.putExtra("hotelId", data.get(currentPosition).getId());
                    intent.putExtra("brokerAge", data.get(currentPosition).getBrokerAgeAmountValue());
                    intent.putExtra("type", 1);
                    startActivity(intent);
                }else {
                    Intent intent = new Intent(getContext(), HouseDetailsActivityFor3.class);
                    intent.putExtra("type", 1);
                    intent.putExtra("houseId", data.get(currentPosition).getHouse().getId());
                    intent.putExtra("presellProduct", data.get(currentPosition).getModelType() == 52);

                    intent.putExtra("brokerAge", data.get(currentPosition).getBrokerAge());
                    intent.putExtra("persellId", data.get(currentPosition).getId());
                    startActivityForResult(intent, 123);
                }*/

            }
            break;
        }

    }

    @Override
    public void onCallback() {
        if (nextIndex == pageNo + 1) {
            pageNo++;
            getData();
        }
    }

    @Override
    public void onResponse(String url, String json) {
        if (statusLayoutManager != null) {

            statusLayoutManager.showSuccessLayout();
        }
        if (Constant.URL.member_favor_list.equals(url)) {
            LogeUtil.e("member_favor_list", json);
            dismissLoading();

            Member_favor_listEntity recommendEntity = gson.fromJson(json, Member_favor_listEntity.class);
            removeLoadingItem();
            if (pageNo == 1) {
                data.clear();
            }

            if ("200".equals(recommendEntity.getCode())) {
                   /* if (pageNo == 1 && presellEntity.getBody().getRecomendList() != null && presellEntity.getBody().getRecomendList().getList() != null) {

                        dataHead.addAll(presellEntity.getBody().getRecomendList().getList());
                        homeListSaleHeadAdapter.setData(dataHead);
                    }*/
                data.addAll(recommendEntity.getBody().getList());
                if (recommendEntity.getBody().isHasNext()) {
                    data.add(new Member_favor_listEntity.BodyEntity.ListEntity(1));
                    nextIndex = pageNo + 1;

                } else {
                    addBaseLine();
                }

            } else {
                addBaseLine();
            }
            favoriteListFindAdapter.setData(data);
        }
    }

    @Override
    public void onFailure(String url, String error) {
        dismissLoading();
        if (statusLayoutManager != null) {

            statusLayoutManager.showErrorLayout();
        }
    }

    private void dismissLoading() {

        if (srl != null && srl.isRefreshing()) {
            srl.setRefreshing(false);
        }
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    private void removeLoadingItem() {
        if (data.size() > 0) {
            if (data.get(data.size() - 1).getMyType() == 1) {
                data.remove(data.size() - 1);
            }
        }
    }

    private void addBaseLine() {
        if (pageNo != 1) {
            data.add(new Member_favor_listEntity.BodyEntity.ListEntity(2));
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 123) {//

            if (resultCode == Activity.RESULT_OK) {

                removeData(currentPosition);
            }
        }
    }

    //  删除数据
    public void removeData(int position) {
        data.remove(position);
        //删除动画
        favoriteListFindAdapter.notifyItemRemoved(position);
        favoriteListFindAdapter.notifyDataSetChanged();

        if (data.size()==1&&nextIndex>1){
            data.remove(0);
            favoriteListFindAdapter.notifyItemRemoved(0);

        }

        //删除动画
        favoriteListFindAdapter.notifyDataSetChanged();
    }



}